package com.aier.entrance.icsocket;




import java.text.SimpleDateFormat;
import java.util.Date;

import javax.annotation.Resource;

import net.eicp.ghostboy.futil.StringUtil;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;

import com.aier.common.common.Constant;
import com.aier.entrance.common.EntranceICFinalData;
import com.aier.entrance.common.EntranceServerData;
import com.aier.entrance.entity.EntranceDevice;
import com.aier.entrance.entity.VideoDevice;
import com.aier.entrance.service.IEntranceCardService;
import com.aier.entrance.service.Snapshot;


public class TestServerSessionHandler extends IoHandlerAdapter {

           //private final Logger log = Logger.getLogger(TestServerSessionHandler .class);
    private final int IDLE = 10;
    private String com;                                            //传回的命令方式
    //private String cardNoArray[];                                //53命令中会传回的卡号数组
    //private String cardNo;                                        //53命令中会传回的卡号
    private String type;                                        //53命令何总门状态事件
    //private String isMore;                                        //是否还有更多记录
    //private String curNum;                                        //当前的记录号
    private String sn;                                            //设备序列号
    //private String command;
    private ReplayMessage replayMessage;
    @Resource(name="entranceCardService")
    private IEntranceCardService ec ;
    long[] flag =new long[]{-1};                            //调用服务器数据库之后的结果                                                
    EntranceDevice ed;
    
    
    @Override
    public void exceptionCaught(IoSession session, Throwable cause)
        throws Exception {
        //session.close();
        //log.error("session occured exception, so close it.");
    }

    @Override
    public void messageReceived(IoSession session, Object message)
        throws Exception {
//      System.out.println("开始时间" + new Date().getTime());
        TestMessage msg = (TestMessage)message;
        System.out.println(Thread.currentThread().getId() + "session" + session.getId() + msg.toString());
        com = msg.getCom();
        switch (Integer.parseInt(com)) {
            case Constant.num_53:{                                                                                    //刷卡记录回应
                type = msg.getType();
                sn = TestMessageDecoder.snMap.get(session.getId() + "");
                ed =EntranceServerData.mapED.get(sn);
                
                /*
                if(type.equals("01")){                                                                //无效卡    
                //    flag = ec.swingICCard(TestMessageDecoder.snMap.get(session.getId() + ""),
                //(cardNo + ""),IEntranceCardService.OPERATE_IN);
                //    System.out.println("设备号" + TestMessageDecoder.snMap.get(session.getId() + "") + "flag:" + flag[0]);
                    sendCommand("2C", "01", "00",new String[]{"01"}, session);
                    
                }else
                */
                
                SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd kk:mm:ss "); 
                System.out.println("刷卡的时间:"+sdf.format(new Date())+"类型type="+type);
                
                System.out.println("门禁刷卡的时间:"+msg.getRecordTime()+"类型type="+type);
                
                if(type.equals("10") || type.equals("83")|| type.equals("03")){                         //进门事件
                    //flag = ec.updateSwingICCard(sn,msg.getCardNo(),IEntranceCardService.OPERATE_IN,msg.getRecordTime());
                    flag = ec.updateSwingICCard(sn,msg.getCardNo(),IEntranceCardService.OPERATE_IN,sdf.format(new Date()));
                    System.out.println("设备号" + TestMessageDecoder.snMap.get(session.getId() + " ") + "flag:" + flag[0]);
                    if((flag[0] == EntranceICFinalData.SWINGICCARD_STATE_USER_SUCCESS)||
                             (flag[0] == EntranceICFinalData.SWINGICCARD_STATE_TEACHER_SUCCESS)||
                                 flag[0] == EntranceICFinalData.SWINGICCARD_STATE_SCHOOL_SUCCESS){
                        sendCommand(com,"01","02", "00", new String[]{msg.getCurNum(),"01"},session);
                        //进行拍照操作    
                        if(flag[0] != EntranceICFinalData.SWINGICCARD_STATE_SCHOOL_SUCCESS){
                            if((EntranceICFinalData.ENTRANCE_VDSTATE_ALL == ed.getVdstate()) || 
                                     (EntranceICFinalData.ENTRANCE_VDSTATE_IN == ed.getVdstate())){
                                System.out.println("in");
                                doSnap(ed,ec.updateImg(flag[2], flag[1],flag[0], IEntranceCardService.OPERATE_IN));
                            }    
                        }
                     
                    }else{
                        sendCommand(com,"01","02", "00", new String[]{msg.getCurNum(),"00"},session);
                        //报警
                        doWarning(session);
                    }
                }else if(type.equals("11") || type.equals("91")|| type.equals("83")|| type.equals("03")){            //出门事件
                    //flag = ec.updateSwingICCard(sn,msg.getCardNo(),IEntranceCardService.OPERATE_OUT,msg.getRecordTime());
                    flag = ec.updateSwingICCard(sn,msg.getCardNo(),IEntranceCardService.OPERATE_OUT,sdf.format(new Date()));
                    System.out.println("设备号" + TestMessageDecoder.snMap.get(session.getId() + " ") + "flag:" + flag[0]);
                    if((flag[0] == EntranceICFinalData.SWINGICCARD_STATE_USER_SUCCESS)||
                             (flag[0] == EntranceICFinalData.SWINGICCARD_STATE_TEACHER_SUCCESS)||
                                 flag[0] == EntranceICFinalData.SWINGICCARD_STATE_SCHOOL_SUCCESS){
                        sendCommand(com,"02","02", "00", new String[]{msg.getCurNum(),"01"},session);
                        //进行拍照操作
                        if(flag[0] != EntranceICFinalData.SWINGICCARD_STATE_SCHOOL_SUCCESS){
                            if((EntranceICFinalData.ENTRANCE_VDSTATE_ALL == ed.getVdstate()) || 
                                    (EntranceICFinalData.ENTRANCE_VDSTATE_OUT == ed.getVdstate())){
                                doSnap(ed,ec.updateImg(flag[2], flag[1],flag[0], IEntranceCardService.OPERATE_OUT));
                            }    
                        }
                        
                    }else{
                        sendCommand(com,"02","02", "00", new String[]{msg.getCurNum(),"00"},session);
                        //报警
                        doWarning(session);
                    }
                }else if(type.equals("00")){
                    sendCommand(com,"00","02", "00", new String[]{msg.getCurNum(),"00"},session);
                }
            
                break;
            }
            case Constant.num_54:{                                                                                    //对报警进行回应
                sendCommand(com,"00","02", "00", new String[]{msg.getCurNum(),"00"},session);
                break;
            }
            case Constant.num_56:{                                                                                    //对记录进行回应
                sendCommand(com,"00","02", "00", new String[]{"00","00"},session);
                break;
            }
            default:
                break;
        }
    //       System.out.println("结束时间" + new Date().getTime());
    }
        
        
    /**
     * 进行报警操作
     * @throws InterruptedException
     */
    public void doWarning(IoSession session) throws InterruptedException{
        //如果打卡不成功,则报警
        sendCommand("18","00","02", "00", new String[]{"00","00"},session);
        //报警1.2秒钟
        Thread.sleep(Constant.num_1200);
        sendCommand("18","00","02", "00", new String[]{"01","00"},session);
    }
        
    /**
     * 进行拍照操作
     */
    public void doSnap(EntranceDevice ed,String filepath){
        VideoDevice vd= ed.getVd();
        String url = "";
        String user = "";
        String pwd = "";
        short supplier;
        
        url = vd.getUrlIP();
        user = vd.getUser();
        pwd = vd.getPwd();
        supplier = vd.getSupplier();
        if(null == pwd){ 
            pwd = "";
        }
        if((!"".equals(url))&&(!StringUtil.isStringNull(filepath))){
            new Snapshot(supplier,url, user, pwd,filepath).start();
        }
        
       
    }
    
    /**
     * @param com        命令
     * @param lengthL   
     * @param lengthH
     * @param data        数据位
     */
    public void sendCommand(String com,String door,String lengthL,String lengthH,String[] data,IoSession session){
        final String stxAndRand = "02 A0";        //开始位和随机数
        final String add = "FF";        //地址和门号    
        final String end = "03";                //结束位
        String cs = "";                            //校验值            
        String command = "";                    //指令
        String dataStr = "";                    //data字符串        
        //02与A0进行异或，则为A2;FF与00 异或则为FF;
        cs = getXorBystr("A2", com);
        cs = getXorBystr(cs, "FF");
        cs = getXorBystr(cs, door);
        cs = getXorBystr(cs, lengthL);
        cs = getXorBystr(cs, lengthH);
        if(data != null){
            for (int i = 0; i < data.length; i++) {
                dataStr += data[i] + " ";
                cs = getXorBystr(cs, data[i]);
            }
        }
        
        replayMessage = new ReplayMessage();
        
        command = stxAndRand + " " + com + " " + add + " " + door + " " + lengthL + " " + lengthH + " " + dataStr
                + cs + " " + end;
        replayMessage.setCommand(command);
    //    System.out.println("命令" + command);
        session.write(replayMessage);    

    }
        

    /**
     * 进行异或操作，得到所需的值
     * @param a        参数a
     * @param b        参数b
     * @return
     */
    public  String getXorBystr(String a, String b){
        String result = "";
        String a1 = a.substring(0, 1);    
        String a2 = a.substring(1, 2);
        String b1 = b.substring(0, 1);    
        String b2 = b.substring(1, 2);

        int a1A = Integer.parseInt(a1, Constant.num_16);
        int a2A = Integer.parseInt(a2, Constant.num_16);
        int b1A = Integer.parseInt(b1, Constant.num_16);
        int b2A = Integer.parseInt(b2, Constant.num_16);
        
        int con = a1A^b1A;
        if(con > Constant.num_9) {result = (char)((con - Constant.num_10) + 'A') + "";}
        else {result = con + "";}
        con = a2A^b2A;
        if(con > Constant.num_9) {result = result + (char)((con - Constant.num_10) + 'A');}
        else {result = result + con;}
        return result;        
    }
    
    

    @Override
    public void messageSent(IoSession session, Object message) throws Exception {
        super.messageSent(session, message);
       //System.out.println("信息发送完");
        session.getConfig().setUseReadOperation(true);

        //session.close();
        //session.getCloseFuture().awaitUninterruptibly();
    }

    @Override
    public void sessionCreated(IoSession session) throws Exception {
        //System.out.println("客户端创建" + session.getId());
        session.getConfig().setIdleTime(IdleStatus.BOTH_IDLE, IDLE);
        //log.info("remote client ["+session.getRemoteAddress().toString()+"] connected.");
        
    }

    @Override
    @SuppressWarnings("deprecation")
    public void sessionIdle(IoSession session, IdleStatus status)
        throws Exception {
      //  log.info("session idle, so disconnecting......");
        
        
        //System.out.println("客户端闲置");
        session.close();
       // log.info("disconnected.");
    }

    @Override
    public void sessionOpened(IoSession session) throws Exception {
        //System.out.println("客户端接入");
        //设置socket空闲时间
        
        //其他配置也在此设置
    }

    public void setEc(IEntranceCardService ec) {
        this.ec = ec;
    }
        
        
}